<template>
  <el-form
    :model="form"
    :rules="rules"
    ref="form"
    class="login-container"
    v-loading="loading"
  >
    <h3 class="title">{{ isRegister ? "注册" : "登录" }}</h3>
    <el-form-item prop="username">
      <el-input
        type="text"
        v-model="form.username"
        auto-complete="off"
        placeholder="用户名"
      />
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        type="password"
        v-model="form.password"
        auto-complete="off"
        placeholder="密码"
      />
    </el-form-item>
    <el-form-item style="width:100%;">
      <el-button
        type="primary"
        style="width:100%;"
        @click.native.prevent="onSubmit"
        :loading="loading"
      >
        {{ isRegister ? "注册" : "登录" }}
      </el-button>
      <el-button type="text" @click="isRegister = true" v-if="!isRegister">
        立即注册
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import sha1 from "sha1";
import chat from "@/mixins/chat.js";
export default {
  mixins: [chat],
  data() {
    return {
      loading: false,
      isRegister: false,
      form: {
        username: "admin",
        password: "admin"
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return;
        this.loading = true;
        try {
          if (!this.isRegister) {
            await this.login(this.form.username, sha1(this.form.password));
            const { userId } = this.$imConn.context;
            this.$message.success("login successfully");
            this.$router.push({
              path: "/chat",
              query: {
                id: userId
              }
            });
          } else {
            await this.register({
              username: this.form.username,
              password: sha1(this.form.password),
              nickname: this.form.username
            });
            this.isRegister = false;
            this.$message.success("register successfully");
          }
        } catch (err) {
          console.log(err);
          // if (!err) return;
          // let data = err.data.data || err.data;
          // this.$message.error(JSON.parse(data).error_description);
        } finally {
          this.loading = false;
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.login-container {
  border-radius: 5px;
  background-clip: padding-box;
  margin: 180px auto;
  width: 350px;
  padding: 35px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
  .title {
    margin: 0px auto 40px auto;
    text-align: center;
    color: #505458;
  }
}
</style>
